import { Service } from 'egg';

import { Result } from '../util/result';
import { v4 as uuidv4 } from 'uuid';
import { put } from '../util/ossFile';
import RoleEnum from '../util/roleEnum';
import MsgEnum from '../util/msgEnum';
import areas from '../util/area';
import {
  typeList,
  conversionTypeList,
  legalStatusList
} from '../../constants/user-role';
export default class Patent extends Service {
  async check(patentNumber) {
    const { ctx } = this;

    const exist = await ctx.model.Patent.findAll({
      where: { applicationNumber: patentNumber },
    });
    if (exist.length === 0) {
      return { state: false };
    }
    return { state: true };

  }

  async delete(patentId: number) {
    let transaction;
    try {
      transaction = await this.ctx.model.transaction();
      console.log(
        await this.ctx.model.MergeProductPatent.destroy({
          where: { patent_id: patentId },
          transaction,
        })
      );
      /* await this.ctx.model.MergePatentTalent.destroy({
        where: { patent_id: patentId },
        transaction,
      }); */
      const result = await this.ctx.model.Patent.destroy({
        where: { id: patentId },
        transaction,
      });

      await transaction.commit();
      return new Result({ result }, MsgEnum.UPLOAD_SUCCESS);
    } catch (e) {
      console.log(e);
      transaction.rollback();
      return new Result(null, MsgEnum.SERVER_ERROR);
    }
  }

  public async getPatentMaps() {
    const mainData = await this.ctx.model.Patent.findAll({ attributes: ['address'] });
    const data: any = {};
    mainData.forEach((v: any) => {
      let add;
      if (v.address?.split(';')[0] === '台湾省') {
        add = '台湾';
      } else {
        add = v.address?.split(';')[1];
      }
      if (!data.hasOwnProperty(add)) {
        data[add] = 1;
      } else {
        data[add]++;
      }
    });
    let dataw = 'lng,lat,name,v\n';
    for (const name in data) {
      if (data.hasOwnProperty(name)) {

        if (areas[name] && name !== undefined && name !== 'undefined') {
          dataw += (areas[name]?.join(',') ?? '0,0') + ',' + name + ',' + data[name] + '\n';
        } else {
          dataw += '\n';
        }
      }
    }
    return dataw;
  }
  async insertPatent(data, r) {
    const { ctx } = this;
    const exist = await ctx.model.Patent.findAll({
      where: { applicationNumber: data.applicationNumber },
    });
    if (data.applicationNumber !== '' && exist.length !== 0) {
      return new Result({ exist: true }, MsgEnum.PROJUCT_REPEAT);
    }
    let transaction;
    try {
      transaction = await this.ctx.model.transaction();
      const uuid = uuidv4().replace(/-/g, '');

      const _area = await ctx.model.ApplicationArea.findOne(
        {
          where: { uuid: data.applicationArea },
        },
        { transaction }
      );

      // 处理申请人公司
      let applicationOrganizationString = '';
      const currentApplicationOrganization =
        data.applicationOrganization.split(',');
      currentApplicationOrganization.forEach(element => {
        applicationOrganizationString += element + ';';
      });

      /* const mergeTalents: number[] = [];
      let talentsString = '';
      const currentTalents = data.talents.split(',');
      currentTalents.forEach(element => {
        if (isNaN(parseInt(element))) {
          // 是未入库人才
          talentsString += element + ';';
        } else {
          mergeTalents.push(parseInt(element));
        }
      });


      const _talents = await ctx.model.Talent.findAll(
        {
          where: {
            id: mergeTalents,
          },
        },
        { transaction }
      ); */

      const ret = await ctx.model.Patent.create(
        {
          name: data.patentName,
          uuid,
          address: data.address,
          applicationNumber: data.applicationNumber,
          applicationTime: data.applicationTime ? new Date(data.applicationTime) : undefined,
          legalStatus: data.legalStatus,
          conversionMethod: data.conversionMethod,
          conversionType: data.conversionType,
          description: data.description,
          technicalAdvantages: data.technicalAdvantages,
          publicNumber: data.publicNumber,
          type: data.type,
          applicationOrganization: applicationOrganizationString, // 申请人（string类型，每个公司中间用;分割）
          talentsString: data.talents,
        },
        { transaction }
      );

      await (ret as any).setApplication_area(_area, { transaction });
      // await (ret as any).setOrganizations(_organizations);
      // await (ret as any).setTalents(_talents, { transaction });
      await transaction.commit();
      const { id } = ret as any;

      console.log(r.filename);

      if (r.filename !== 'null.pdf') {
        const res = await put(RoleEnum.PATENT, id, r);

        if (res.error) {
          return new Result(null, MsgEnum.SERVER_ERROR);
        }
      }

      return new Result({ upload: true }, MsgEnum.UPLOAD_SUCCESS);
    } catch (e) {
      console.log('e:============', e);

      await transaction.rollback();
      return new Result(null, MsgEnum.SERVER_ERROR);
    }
  }

  async updatePatent(data, r) {
    const { ctx } = this;
    let transaction;
    try {
      transaction = await this.ctx.model.transaction();

      const _area = await ctx.model.ApplicationArea.findOne(
        {
          where: { uuid: data.applicationArea },
        },
        { transaction }
      );

      const ret = await ctx.model.Patent.findOne({
        where: {
          id: Number(data.id),
        },
        transaction,
      });
      await ret?.update({
        conversionMethod: data.conversionMethod,
        conversionType: data.conversionType,
        description: data.description,
        technicalAdvantages: data.technicalAdvantages,
      });

      await (ret as any).setApplication_area(_area, { transaction });
      // await (ret as any).setOrganizations(_organizations);
      await transaction.commit();
      const { id } = ret as any;
      console.log(r.filename);

      if (r.filename !== 'null.pdf') {
        const res = await put(RoleEnum.PATENT, id, r);

        if (res.error) {
          return new Result(null, MsgEnum.SERVER_ERROR);
        }
      }

      return new Result({ upload: true }, MsgEnum.UPLOAD_SUCCESS);
    } catch (e) {
      console.log('e:============', e);

      await transaction.rollback();
      return new Result(null, MsgEnum.SERVER_ERROR);
    }
  }

  public async createUploadPatent(
    patentName,
    applicationArea,
    type,
    applicationOrganization,
    talents,
    conversionMethod,
    conversionType,
    address,
    legalStatus,
    publicNumber,
    applicationNumber,
    applicationTime,
    description,
    technicalAdvantages
  ) {
    let transaction;
    try {
      const contains = function (arr, obj) {
        let i = arr.length;
        while (i--) {
          if (arr[i] === obj) {
            return true;
          }
        }
        return false;
      };
      let isTrue = true;
      let message = '';
      const { ctx } = this;
      transaction = await this.ctx.model.transaction();
      const exist = await ctx.model.Patent.findAll({
        where: { applicationNumber: applicationNumber ?? '' },
      });
      const applicationAreaDefault = await ctx.model.ApplicationArea.findAll({
        attributes: ['name'],
      });
      const applicationData = applicationAreaDefault.map(v => {
        return v.name;
      });

      if (applicationNumber !== '' && applicationNumber !== undefined && exist.length !== 0) {
        isTrue = false;
        message = message + '已有相同申请号的专利存在';
        return {
          state: 'false',
          message,
        };
      }
      if (!contains(applicationData, applicationArea)) {
        isTrue = false;
        message = message + '应用领域不存在';
      }
      if (!contains(typeList, type)) {
        isTrue = false;
        message = message + '专利类型不存在';
      }
      // if (!contains(conversionMethodList, conversionMethod)) {
      //   isTrue = false;
      //   message = message + '转化方式不存在';
      // }
      if (!contains(conversionTypeList, conversionType)) {
        isTrue = false;
        message = message + '转化状态不存在';
      }
      if (!contains(legalStatusList, legalStatus)) {
        isTrue = false;
        message = message + '法律状态不存在';
      }
      if (isTrue) {
        const _aera = await ctx.model.ApplicationArea.findOne({
          where: { name: applicationArea },
        });


        const ret = await ctx.model.Patent.create(
          {
            name: patentName,
            uuid: uuidv4(),
            address,
            applicationNumber,
            applicationTime:
              Number(applicationTime) + '' !== NaN + ''
                ? new Date((applicationTime - 25569) * 24 * 60 * 60 * 1000)
                : applicationTime,
            legalStatus,
            conversionMethod,
            conversionType,
            description,
            technicalAdvantages,
            publicNumber,
            applicationOrganization, // 申请人（string类型，每个公司中间用;分割）
            talentsString: talents,
            type,
          },
          { transaction }
        );

        await (ret as any).setApplication_area(_aera, { transaction });
        await ret.save();
        transaction.commit();
        return {
          state: 'true',
        };
      }
      return {
        state: 'false',
        message,
      };


    } catch (e) {
      console.log(e);
      transaction.rollback();
    }
  }
}
